<template>
  <q-dialog
    no-backdrop-dismiss
    v-model="recordDetailVisible"
    square
    position="standard"
  >
    <q-card style="width: 800px; max-width: 80vw">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">
          {{ formTypeName }} {{ $t("Sqlparam") }}:
          {{ recordDetail.value.sqlparam_code }}
          <!-- {{ dictOptions.sqlparamType }} -->
        </div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-separator />

      <q-card-section>
        <q-form ref="recordDetailForm">
          <!-- <div>{{ LegitSqlparamType }}</div> -->
          <q-field :label="$t('Sqlparam') + $t('Type')" stack-label>
            <template v-slot:control>
              <q-option-group
                v-model="recordDetail.value.sqlparam_type"
                :options="LegitSqlparamType"
                color="primary"
                inline
                @update:model-value="handleSqlparamTypeChange"
              >
              </q-option-group>
            </template>
          </q-field>
          <q-input
            filled
            clearable
            v-model="recordDetail.value.sqlparam_code"
            label="SQL参数编码(英文)"
            :rules="[(val) => (val && val.length > 0) || '必须输入SQL参数编码']"
          >
          </q-input>
          <q-input
            filled
            clearable
            v-model="recordDetail.value.sqlparam_name"
            label="SQL参数名"
            :rules="[(val) => (val && val.length > 0) || '必须输入SQL参数名']"
          >
          </q-input>

          <q-input
            clearable
            filled
            class="q-mb-md"
            type="textarea"
            stack-label
            autogrow
            v-if="recordDetail.value.sqlparam_type === 'optionsFromPreDefined'"
            v-model="recordDetail.value.options"
            label="选项(请用逗号分隔)"
          ></q-input>
          <q-input
            filled
            class="q-mb-md"
            stack-label
            clearable
            v-if="recordDetail.value.sqlparam_type === 'optionsFromQuery'"
            v-model="recordDetail.value.option_sql"
            label="查询语句(只允许select一列数据作为选项)"
          >
            <template v-slot:append>
              <q-btn
                push
                color="secondary"
                @click="validateSqlparamOptionSql"
                :label="$t('Validate') + $t('Sql') + $t('Statement')"
              />
            </template>
          </q-input>
          <q-input
            filled
            stack-label
            clearable
            :type="getType"
            v-model="recordDetail.value.default_value"
            label="默认值"
          >
            <template v-slot:append>
              <q-btn
                v-if="recordDetail.value.use_variable === 'yes'"
                push
                color="secondary"
                @click="validateVariable"
                :label="$t('Validate') + $t('Sqlparam') + $t('Variable')"
              />
            </template>
          </q-input>

          <q-checkbox
            v-model="recordDetail.value.use_variable"
            v-if="recordDetail.value.sqlparam_type === 'date'"
            color="primary"
            true-value="yes"
            false-value="no"
            indeterminate-value="no"
            >日期默认值使用变量定义(请使用Postgresql语法，如current_date-1或(current_date
            - interval'1 month')::date，请保证输出为YYYY-MM-DD格式！
          </q-checkbox>
        </q-form>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          label="保存"
          color="primary"
          @click="handleAddOrEditAfterPassed"
        />
        <q-btn label="取消" color="negative" v-close-popup />
      </q-card-actions>

      <q-inner-loading :showing="loading">
        <q-spinner-gears size="50px" color="primary" />
      </q-inner-loading>
    </q-card>
  </q-dialog>
</template>

<script setup>
import useRecordDetail from "src/composables/useRecordDetail";
import { postAction } from "src/utils/requestAction";
import { useStorageStore } from "src/stores/storage";
import { computed, ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";

const $q = useQuasar();
const { t } = useI18n();
const emit = defineEmits(["handleFinish"]);
const url = {
  add: "sqlparam/add-sqlparam",
  edit: "sqlparam/edit-sqlparam",
  queryById: "sqlparam/query-sqlparam-by-id",
  validateVariable: "sqlparam/validate-variable",
  validateSqlparamOptionSql: "sqlparam/validate-sqlparam-option-sql",
};

const defaults = {
  sqlparam_type: "text",
  sqlparam_code: "",
  sqlparam_name: "",
  default_value: "",
  option_sql: "",
  options: "",
  use_variable: "no",
};
const passed = ref(false);

const LegitSqlparamType = computed(() => {
  // console.log(dictOptions);
  return dictOptions.value.sqlparamType.filter((item) => {
    return item.value !== "internal";
  });
});

const handleAddOrEditAfterPassed = () => {
  if (
    recordDetail.value.sqlparam_type === "optionsFromQuery" &&
    !passed.value
  ) {
    $q.dialog({
      title: "需要校验SQL",
      message: "尚未通过校验或上次校验后修改了SQL, 请先测试SQL是否合法!",
    });
  } else if (
    recordDetail.value.sqlparam_type === "date" &&
    recordDetail.value.use_variable == "yes" &&
    !passed.value
  ) {
    $q.dialog({
      title: "需要校验日期参数变量",
      message:
        "尚未通过校验或上次校验后修改了日期参数变量, 请先测试日期参数变量是否合法!",
    });
  } else {
    handleAddOrEdit();
  }
};

const validateVariable = async () => {
  const variable_string = recordDetail.value.default_value;
  const sqlParams = {
    variable_string: variable_string,
  };
  await postAction(url.validateVariable, sqlParams).then((res) => {
    //console.log(res);
    passed.value = res.code === 1 ? true : false;
    $q.dialog({
      title: "测试结果",
      message:
        res.code === 1
          ? res.message + "当前默认值为：" + res.data.records
          : res.message,
    });
  });
};

const validateSqlparamOptionSql = async () => {
  const option_sql = recordDetail.value.option_sql;
  const sqlParams = {
    sql_string: option_sql,
  };
  await postAction(url.validateSqlparamOptionSql, sqlParams).then((res) => {
    //console.log(res);
    passed.value = res.code === 1 ? true : false;
    $q.dialog({
      title: "测试结果",
      message:
        res.code === 1
          ? "测试Sql通过! 第一个参数值为：" + res.data.records
          : res.message,
    });
  });
};

const {
  dictOptions,
  formType,
  formTypeName,
  recordDetail,
  recordDetailVisible,
  loading,
  show,
  recordDetailForm,
  handleAddOrEdit,
} = useRecordDetail(url, emit, defaults);

onMounted(() => {
  console.log(formTypeName);
  if (formType === "add") {
    recordDetail.value.sqlparam_type = "string";
  }
});

const getType = computed(() => {
  if (
    recordDetail.value.sqlparam_type === "date" &&
    recordDetail.value.use_variable != "yes"
  ) {
    return "date";
  } else {
    return "text";
  }
});

defineExpose({
  show,
  formType,
  recordDetail,
});

const handleSqlparamTypeChange = (val) => {
  recordDetail.value.default_value = "";
  recordDetail.value.use_variable = "no";
  recordDetail.value.options = "";
  recordDetail.value.option_sql = "";
  passed.value = false;
};
</script>

<script>
import { defineComponent } from "vue";

export default defineComponent({
  name: "SqlparamRecordDetail",
});
</script>
